﻿using System;
using System.Diagnostics;
using log4net;

namespace Client.Host.Infrastructure.Logging
{
    public class Log4NetLogger : ILogger
    {
        public void LogVerbose(string message)
        {
            LogIf(x => x.IsDebugEnabled, y => y.Debug(message));
        }

        public void LogVerboseFormat(string message, params object[] args)
        {
            LogIf(x => x.IsDebugEnabled, y => y.DebugFormat(message, args));
        }

        public void LogInfo(string message)
        {
            LogIf(x => x.IsInfoEnabled, y => y.Info(message));
        }

        public void LogInfoFormat(string message, params object[] args)
        {
            LogIf(x => x.IsInfoEnabled, y => y.InfoFormat(message,args));
        }

        public void LogWarning(string message)
        {
            LogIf(x => x.IsWarnEnabled, y => y.Warn(message));
        }

        public void LogWarningFormat(string message, params object[] args)
        {
            LogIf(x => x.IsWarnEnabled, y => y.WarnFormat(message, args));
        }

        public void LogError(string message)
        {
            LogIf(x => x.IsErrorEnabled, y => y.Error(message));
        }

        public void LogErrorFormat(string message, params object[] args)
        {
            LogIf(x => x.IsErrorEnabled, y => y.ErrorFormat(message, args));
        }

        public void LogError(string message, Exception exception)
        {
            LogIf(x => x.IsErrorEnabled, y => y.Error(message, exception));
        }

        private static void LogIf(Func<ILog, bool> condition, Action<ILog> action)
        {
            ILog logger = GetLogger();
            if (condition(logger))
            {
                action(logger);
            }
        }
        
        private static ILog GetLogger()
        {
            var stack = new StackTrace();
            var frame = stack.GetFrame(2);
            return LogManager.GetLogger(frame.GetMethod().DeclaringType);
        }
    }
}
